const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin'); //清空文件
const ExtractTextPlugin = require("extract-text-webpack-plugin");   //提取css


module.exports = {
    devtool: 'cheap-module-source-map',
    /*入口*/
    entry: {
        app: [
        'react-hot-loader/patch',
        path.join(__dirname, 'src/index.js')
        ],
        vendor: ['react', 'react-router-dom', 'redux', 'react-dom', 'react-redux']
    },
    
    /*输出到dist文件夹，输出文件名字为bundle.js*/
    output: {
        path: path.join(__dirname, './dist'),
        publicPath : './',   //静态资源相对于当前路径
        filename: '[name].[hash:8].js',
        chunkFilename: '[name].[chunkhash:8].js'
    },
     /*src文件夹下面的以.js结尾的文件，要使用babel解析*/
     /*cacheDirectory是用来缓存编译结果，下次编译加速*/
    module: {
        rules: [
            {
                test: /\.js$/,
                use: ['babel-loader?cacheDirectory=true'],
                include: path.join(__dirname, 'src')
            },
            // 样式
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                  fallback: "style-loader",
                  use: "css-loader"
                })
            },
            // 图片
            {
                test: /\.(png|jpg|gif)$/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 8192 //这里是8K
                    }
                }]
            }
        ]
    },
    // 本地路径别名化 
    resolve: {
        alias: {
            pages: path.join(__dirname, 'src/pages'),
            component: path.join(__dirname, 'src/component'),
            router: path.join(__dirname, 'src/router'),
            actions: path.join(__dirname, 'src/redux/actions'),
            reducers: path.join(__dirname, 'src/redux/reducers'),
            // redux: path.join(__dirname, 'src/redux')

        }
    },
  
    plugins:[
        // 清空文件 
        new CleanWebpackPlugin(['dist/*.*']),
        // 热更新
        new webpack.HotModuleReplacementPlugin(),
        // 根据模块建立INDEX页面
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: path.join(__dirname, 'src/index.html')
        }),
        // 提取css
        new ExtractTextPlugin({
            filename: '[name].[contenthash:5].css',
            allChunks: true
        }),
        new webpack.HashedModuleIdsPlugin(),
        // 抽离的公共文件
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor'
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'runtime'
        }),
        // 混淆压缩
        new UglifyJSPlugin(),
        // 更强的压缩
        new webpack.DefinePlugin({
          'process.env': {
              'NODE_ENV': JSON.stringify('production')
           }
       })
    ]
};